package other;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 
 * @author Administrator 采用Dom4j解析复杂的xml文件
 *
 */
public class Dom4jParseXml {

	/**
	 * Dom4j解析xml文件的代码片段
	 * 
	 * @throws DocumentException
	 */

	// 设置数据存储格式Map

	private static Map<String, Object> map = new HashMap<String, Object>();

	public static Map<String, Object> parseXml(File filePath) throws DocumentException {

		Map<String, Object> mapEle = new HashMap<String, Object>();
		// StringBuffer sb = new StringBuffer();
		SAXReader reader = new SAXReader();
		Document document = reader.read(filePath);// 读取xml文档
		Element root = document.getRootElement();// 得到xml文档根节点元素，即最上层的"<xml>"
		// System.out.println("输出根节点元素的名字===" + root.getName());

		// 循环遍历出更节点下面的子节点
		List<Element> elementList = root.elements();

		Iterator<Element> it = elementList.iterator();
		while (it.hasNext()) {
			Element element = it.next();
			// System.out.println(element);
			mapEle = printEle(element);

		}
		return mapEle;
	}

	public static Map<String, Object> printEle(Element ele) {
		// StringBuffer sb = new StringBuffer();
		if (ele.elements().size() == 0) {

			System.out.println("该节点没有子节点，打印出节点名称" + ele.getParent().getName() + "打印出节点的值" + ele.getText());
			map.put(ele.getParent().getName(), ele.getText());
		} else {
			List<Element> elementList = ele.elements();
			Iterator<Element> it = elementList.iterator();
			while (it.hasNext()) {

				printEle(it.next());
			}

		}
		return map;
	}

	/**
	 * @param args
	 *            功能测试
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File file = new File("c:/ttt.xml");
		Map<String, Object> mapEleList = new HashMap<String, Object>();
		// StringBuffer sb = new StringBuffer();
		try {
			mapEleList = Dom4jParseXml.parseXml(file);

			// 遍历map

			Iterator<Entry<String, Object>> it = mapEleList.entrySet().iterator();
			while (it.hasNext()) {

				Entry<String, Object> entry = it.next();

				System.out.println(entry.getKey() + "-------" + entry.getValue());
			}
			// System.out.println(sb.toString());

		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
